
/**
  ******************************************************************************
  * Copyright 2021 The Microbee Authors. All Rights Reserved.
  * 
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  * 
  * http://www.apache.org/licenses/LICENSE-2.0
  * 
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  * 
  * @file       gcs_signing.c
  * @author     baiyang
  * @date       2022-11-4
  ******************************************************************************
  */

/*----------------------------------include-----------------------------------*/
#include "gcs.h"

#include <rtthread.h>

#include <common/time/gp_time.h>
#include <board_config/borad_config.h>
#include <storage_manager/storage_manager.h>
/*-----------------------------------macro------------------------------------*/
// magic for versioning of the structure
#define SIGNING_KEY_MAGIC 0x3852fcd1
/*----------------------------------typedef-----------------------------------*/

/*---------------------------------prototype----------------------------------*/

/*----------------------------------variable----------------------------------*/
struct StorageAccess _signing_storage;

mavlink_signing_streams_t gcs_signing_streams;
uint32_t gcs_last_signing_save_ms;

static const uint32_t accept_list[] = {
    MAVLINK_MSG_ID_RADIO_STATUS,
    MAVLINK_MSG_ID_RADIO
};
/*-------------------------------------os-------------------------------------*/

/*----------------------------------function----------------------------------*/
bool gcsmav_signing_key_save(const struct SigningKey *key)
{
    if (_signing_storage.type != StorageKeys) {
        StorageAccess_init(&_signing_storage, StorageKeys);
    }

    if (StorageAccess_size(&_signing_storage) < sizeof(struct SigningKey)) {
        return false;
    }
    return StorageAccess_write_block(&_signing_storage, 0, key, sizeof(struct SigningKey));
}

bool gcsmav_signing_key_load(struct SigningKey *key)
{
    if (_signing_storage.type != StorageKeys) {
        StorageAccess_init(&_signing_storage, StorageKeys);
    }

    if (StorageAccess_size(&_signing_storage) < sizeof(struct SigningKey)) {
        return false;
    }
    if (!StorageAccess_read_block(&_signing_storage, key, 0, sizeof(struct SigningKey))) {
        return false;
    }
    if (key->magic != SIGNING_KEY_MAGIC) {
        return false;
    }
    return true;
}

/*
  handle a setup_signing message
 */
void gcsmav_handle_setup_signing(gcs_mavlink_t gcsmav, const mavlink_message_t *msg)
{
    // setting up signing key when armed generally not useful /
    // possibly not a good idea
    if (brd_get_soft_armed()) {
        gcsmav_send_text(gcsmav, MAV_SEVERITY_WARNING, "ERROR: Won't setup signing when armed");
        return;
    }

    // decode
    mavlink_setup_signing_t packet;
    mavlink_msg_setup_signing_decode(msg, &packet);

    struct SigningKey key;
    key.magic = SIGNING_KEY_MAGIC;
    key.timestamp = packet.initial_timestamp;
    rt_memcpy(key.secret_key, packet.secret_key, 32);

    if (!gcsmav_signing_key_save(&key)) {
        gcsmav_send_text(gcsmav, MAV_SEVERITY_WARNING, "ERROR: Failed to save signing key");
        return;
    }

    // activate it immediately on all links:
    for (uint8_t i=0; i<MAVLINK_COMM_NUM_BUFFERS; i++) {
        gcs_mavlink_t backend = gcs_chan(i);
        if (backend == NULL) {
            return;
        }
        gcsmav_load_signing_key(backend);
    }
}

static bool accept_unsigned_callback(const mavlink_status_t *status, uint32_t msgId)
{
    if (status == mavlink_get_channel_status(MAVLINK_COMM_0)) {
        // always accept channel 0, assumed to be secure channel. This
        // is USB on PX4 boards
        return true;
    }
    for (uint8_t i=0; i<ARRAY_SIZE(accept_list); i++) {
        if (accept_list[i] == msgId) {
            return true;
        }
    }
    return false;
}

/*
  load signing key
 */
void gcsmav_load_signing_key(gcs_mavlink_t gcsmav)
{
    struct SigningKey key;
    if (!gcsmav_signing_key_load(&key)) {
        return;
    }
    mavlink_status_t *status = mavlink_get_channel_status(gcsmav->chan);
    if (status == NULL) {
        gcsmav_send_text(gcsmav, MAV_SEVERITY_WARNING, "Failed to load signing key - no status");
        return;        
    }

    rt_memcpy(gcsmav->signing.secret_key, key.secret_key, 32);
    gcsmav->signing.link_id = (uint8_t)gcsmav->chan;

    // use a timestamp 1 minute past the last recorded
    // timestamp. Combined with saving the key once every 30s this
    // prevents a window for replay attacks
    gcsmav->signing.timestamp = key.timestamp + 60UL * 100UL * 1000UL;
    gcsmav->signing.flags = MAVLINK_SIGNING_FLAG_SIGN_OUTGOING;
    gcsmav->signing.accept_unsigned_callback = accept_unsigned_callback;

    // if timestamp and key are all zero then we disable signing
    bool all_zero = (key.timestamp == 0);
    for (uint8_t i=0; i<sizeof(key.secret_key); i++) {
        if (gcsmav->signing.secret_key[i] != 0) {
            all_zero = false;
            break;
        }
    }
    if (all_zero) {
        // disable signing
        status->signing = NULL;
        status->signing_streams = NULL;
    } else {
        status->signing = &gcsmav->signing;
        status->signing_streams = &gcs_signing_streams;
    }
}

/*
  update signing timestamp. This is called when we get GPS lock
  timestamp_usec is since 1/1/1970 (the epoch)
 */
void gcsmav_update_signing_timestamp(uint64_t timestamp_usec)
{
    uint64_t signing_timestamp = (timestamp_usec / (1000*1000ULL));
    // this is the offset from 1/1/1970 to 1/1/2015
    const uint64_t epoch_offset = 1420070400;
    if (signing_timestamp > epoch_offset) {
        signing_timestamp -= epoch_offset;
    }

    // convert to 10usec units
    signing_timestamp *= 100 * 1000ULL;

    // increase signing timestamp on any links that have signing
    for (uint8_t i=0; i<MAVLINK_COMM_NUM_BUFFERS; i++) {
        mavlink_channel_t chan = (mavlink_channel_t)(MAVLINK_COMM_0 + i);
        mavlink_status_t *status = mavlink_get_channel_status(chan);
        if (status && status->signing && status->signing->timestamp < signing_timestamp) {
            status->signing->timestamp = signing_timestamp;
        }
    }

    // save to stable storage
    gcsmav_save_signing_timestamp(true);
}


/*
  save the signing timestamp periodically
 */
void gcsmav_save_signing_timestamp(bool force_save_now)
{
    uint32_t now = time_millis();
    // we save the timestamp every 30s, unless forced by a GPS update
    if (!force_save_now &&  now - gcs_last_signing_save_ms < 30*1000UL) {
        return;
    }

    gcs_last_signing_save_ms = now;

    struct SigningKey key;
    if (!gcsmav_signing_key_load(&key)) {
        return;
    }
    bool need_save = false;

    for (uint8_t i=0; i<MAVLINK_COMM_NUM_BUFFERS; i++) {
        mavlink_channel_t chan = (mavlink_channel_t)(MAVLINK_COMM_0 + i);
        const mavlink_status_t *status = mavlink_get_channel_status(chan);
        if (status && status->signing && status->signing->timestamp > key.timestamp) {
            key.timestamp = status->signing->timestamp;
            need_save = true;
        }
    }
    if (need_save) {
        // save updated key
        gcsmav_signing_key_save(&key);
    }
}

/*
  return true if signing is enabled on this channel
 */
bool gcsmav_signing_enabled(gcs_mavlink_t gcsmav)
{
    const mavlink_status_t *status = mavlink_get_channel_status(gcsmav->chan);
    if (status->signing && (status->signing->flags & MAVLINK_SIGNING_FLAG_SIGN_OUTGOING)) {
        return true;
    }
    return false;
}

/*
  return packet overhead in bytes for a channel
 */
uint8_t gcsmav_packet_overhead_chan(mavlink_channel_t chan)
{
    /*
      reserve 100 bytes for parameters when a GCS fails to fetch a
      parameter due to lack of buffer space. The reservation lasts 2
      seconds
     */
    uint8_t reserved_space = 0;
    if (gcs_reserve_param_space_start_ms != 0 &&
        time_millis() - gcs_reserve_param_space_start_ms < 2000) {
        reserved_space = 100;
    } else {
        gcs_reserve_param_space_start_ms = 0;
    }
    
    const mavlink_status_t *status = mavlink_get_channel_status(chan);
    if (status->signing && (status->signing->flags & MAVLINK_SIGNING_FLAG_SIGN_OUTGOING)) {
        return MAVLINK_NUM_NON_PAYLOAD_BYTES + MAVLINK_SIGNATURE_BLOCK_LEN + reserved_space;
    }
    return MAVLINK_NUM_NON_PAYLOAD_BYTES + reserved_space;
}

/*------------------------------------test------------------------------------*/


